<template>
  <div class="app-container">

    <el-steps :active="2" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="最终发布"/>
    </el-steps>

    <el-card class="box-card">
      <!-- 添加课程分类按钮 -->
      <el-button
        type="text"
        @click="openDialog"
        style="font-size: 17px;">点击添加课程分类
      </el-button>

      <!-- 树形结构数据显示 -->
      <div id="chapter">

        <el-tree
          :data="chapterVideoList"
          :props="defaultProps"
          node-key="id"
          :highlight-current="true"
          ref="terr"
          accordion>
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>

                <!-- 添加小结 -->
                <el-button
                  type="text"
                  size="mini"
                  @click="openVideo(node, data)"
                  v-if="node.parent.data.length > 0">
                  添加小结
                </el-button>

                <!-- 编辑章节 -->
                <el-button
                  type="text"
                  size="mini"
                  @click="openUpdateChapter(node, data.id)"
                  v-if="node.parent.data.length > 0">
                  编辑
                </el-button>

                <!-- 编辑小结 -->
                <el-button
                  type="text"
                  size="mini"
                  @click="openVideo(node, data)"
                  v-if="!node.parent.data.length > 0">
                  编辑
                </el-button>

                <!-- 删除章节 -->
                <el-button
                  type="text"
                  size="mini"
                  @click="deleteChapterById(data.id)"
                  v-if="node.parent.data.length > 0">
                  删除
                </el-button>

                <!-- 删除小结 -->
                <el-button
                  type="text"
                  size="mini"
                  @click="deleteVideo(data.id)"
                  v-if="!node.parent.data.length > 0">
                  删除
                </el-button>
              </span>
          </span>
        </el-tree>

        <!--        &lt;!&ndash; 插入后显示数据 &ndash;&gt;-->
        <!--        <el-collapse accordion>-->
        <!--          &lt;!&ndash; 标题数据绑定 &ndash;&gt;-->
        <!--          <el-collapse-item-->
        <!--            v-for="chapter in chapterVideoList"-->
        <!--            :key="chapter.id"-->
        <!--            :title="chapter.title"-->
        <!--            :name="chapter.id"-->
        <!--            class="chapter">-->
        <!--            &lt;!&ndash;  小结数据绑定  &ndash;&gt;-->
        <!--            <div class="video" v-if="chapter.children.length === 0">-->
        <!--              您还没有添加小结-->
        <!--            </div>-->
        <!--            <div v-for="video in chapter.children" :key="video.id" class="video">-->
        <!--              {{ video.title }}-->
        <!--            </div>-->
        <!--          </el-collapse-item>-->
        <!--        </el-collapse>-->
      </div>

      <!-- 添加章节表单 -->
      <el-dialog title="添加课程分类" :visible.sync="dialogFormChapter">
        <el-form :model="chapter" label-width="120px">
          <el-form-item label="章节标题">
            <el-input v-model="chapter.title"/>
          </el-form-item>
          <el-form-item label="章节排序">
            <el-input-number v-model="chapter.sort" :min="0" controls-position="right"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 添加小结弹框 -->
      <el-dialog :visible.sync="dialogFormVideo" title="添加课时">
        <el-form
          :model="video"
          label-width="120px"
          :rules="rules" ref="video">
          <el-form-item label="课时标题" prop="title">
            <el-input v-model="video.title"/>
          </el-form-item>
          <el-form-item label="课时排序" prop="sort">
            <el-input-number v-model="video.sort" :min="0" controls-position="right"/>
          </el-form-item>
          <el-form-item label="是否免费" prop="isFree">
            <el-radio-group v-model="video.isFree">
              <el-radio :label="true">免费</el-radio>
              <el-radio :label="false" :disabled="price === 0">默认</el-radio>
            </el-radio-group>
            <el-tooltip placement="right-end" v-if="price === 0" content="价格设置为0元将只能添加免费章节，如需修改请返回上一步">
              <i class="el-icon-question"/>
            </el-tooltip>
          </el-form-item>

          <!-- 添加视频 -->
          <el-form-item label="上传视频" prop="videoSourceId">
            <el-upload
              :on-success="handleVodUploadSuccess"
              :on-remove="handleVodRemove"
              :before-remove="beforeVodRemove"
              :on-exceed="handleUploadExceed"
              :show-file-list="true"
              :file-list="fileList"
              :action="BASE_API+'/edu_vod/video/uploadAliyunVideo'"
              :limit="1"
              class="upload-demo">
              <el-button size="small" type="primary">上传视频</el-button>
              <el-tooltip placement="right-end">
                <div slot="content">最大支持5G，<br>
                  支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br>
                  GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br>
                  MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br>
                  SWF、TS、VOB、WMV、WEBM 等视频格式上传
                </div>
                <i class="el-icon-question"/>
              </el-tooltip>
<!--              <el-progress :percentage="videoUploadPercent"-->
<!--                           stroke-width="5"></el-progress>-->
<!--              <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>-->
            </el-upload>

          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeVideo">取 消</el-button>
          <el-button :disabled="test" type="primary" @click="videoSaveOrUpdate('video',video)">确 定</el-button>
        </div>
      </el-dialog>

      <el-form label-width="120px" style="text-align: center; padding-top: 50px; padding-right: 150px">
        <el-form-item>
          <el-button @click="previous">上一步</el-button>
          <el-button :disabled="saveBtnDisabled" type="primary" @click="next">下一步</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import chapter from "@/api/edu/chapter";
import video from "@/api/edu/video";
import course from "@/api/edu/course"

export default {
  data() {
    return {
      saveBtnDisabled: false,
      courseId: '',
      chapterVideoList: [],
      dialogFormChapter: false,
      dialogFormVideo: false,
      fileList: [],
      BASE_API: process.env.BASE_API, // 接口地址
      price: 1,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      chapter: {
        title: '',
        sort: 0
      },
      video: {
        title: '',
        sort: 0,
        isFree: 0,
        videoSourceId: '',
        videoOriginalName: ''
      },
      videoFlag: false,
      videoUploadPercent: 0,
      // 表单验证
      rules:{
        title: [{ required: true, message: '请输入小结名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入课程排序', trigger: 'blur' }],
        isFree: [{ required: true, message: '请选择是否免费', trigger: 'blur' }],
        videoSourceId: [{ required: true, message: '请上传视频', trigger: 'blur' }],
      },
    }
  },
  created() {
    // 获取路由上的id
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id
    }
    this.getChapterVideo()
    this.getPrice();
  },
  methods: {
    /* =======================================小结部分======================================= */
    // 上传成功方法
    handleVodUploadSuccess(response, file, fileList) {
      // 保存视频id
      this.video.videoSourceId = response.data.videoId
      // 保存视频名称
      this.video.videoOriginalName = file.name
    },
    // 获取价格
    getPrice() {
      course.getCourseInfoId(this.courseId)
        .then(res => {
          this.price = res.data.courseInfoVO.price
        })
    },
    // uploadVideoProcess(event, file, fileList){
    //   this.videoFlag = true;
    //   this.videoUploadPercent = file.percentage.toFixed(0);
    // },
    // 删除成功方法
    handleVodRemove() {
      video.deleteAliyunVideo(this.video.videoSourceId)
        .then(res => {
          this.$message({
            type: 'success',
            message: '删除视频成功'
          })
          // 清空文件列表
          this.fileList = []
          // 清空视频数据
          this.video.videoSourceId = ''
          this.video.videoOriginalName = ''
        })
    },
    // 删除之前方法
    beforeVodRemove(file, fileList) {
      return this.$confirm(`确定移除${ file.name }`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
    },
    // 提示方法
    handleUploadExceed() {
      this.$message.warning('想要重新上传视频，请先删除已上传视频')
    },
    // 修改小结
    updateVideoById(tvideo) {
      video.updateVideo(tvideo)
        .then(res => {
          this.$message({
            type: 'success',
            message: '修改小结成功'
          })
          this.closeVideo()
        })
    },
    // 删除小结
    deleteVideo(videoId) {
      this.$confirm('此操作将会删除当前小节是否继续', '提示', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          video.deleteVideo(videoId).then(res => {
            this.$message({
              type: 'success',
              message: '删除小节成功'
            })
            // 刷新章节
            this.getChapterVideo()
          })
        })
        .catch(res => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 打开小结弹框
    openVideo(node, data) {
      this.dialogFormVideo = true
      // 清除表单数据
      this.video.title = ''
      this.video.sort = 1
      this.video.isFree = true
      // 清空fileList数据
      this.fileList = []
      // 如果是修改那么就回显数据
      if (data.children == null) {
        // 获取视频小结
        video.getVideo(data.id)
          .then(res => {
            this.video = res.data.video
            this.fileList.push({
              "name": this.video.videoOriginalName
            })
          })
      } else {
        this.video.chapterId = data.id
      }
    },
    closeVideo() {
      this.dialogFormVideo = false
    },
    videoSave() {
      this.video.courseId = this.courseId
      video.addVideo(this.video)
        .then(res => {
          // 关闭弹框
          this.closeVideo()
          // 提示信息
          this.$message({
            type: 'success',
            message: '添加小结成功'
          })
          this.getChapterVideo()
        })
    },
    videoSaveOrUpdate(resVideo, video) {
      this.$refs[resVideo].validate((valid) => {
        if (valid) {
          if (!video.id) {
            this.videoSave()
          }else {
            this.updateVideoById(video)
          }
        } else {
          return false;
        }
      });

    },
    /* =======================================删除章节部分======================================= */
    // 打开修改章节弹框
    openUpdateChapter(node, chapterId) {
      // 显示弹框
      this.dialogFormChapter = true
      // 调用接口
      chapter.getChapterInfo(chapterId)
        // 数据回显
        .then(res => {
          this.chapter = res.data.chapter
        })
    },
    // 打开添加章节框
    openDialog() {
      this.chapter.id = null
      this.dialogFormChapter = true

      // 清空数据
      this.chapter.title = ''
      this.chapter.sort = 0
    },
    // 根据课程id查询章节和小结
    getChapterVideo() {
      chapter.getAllChapterVideo(this.courseId)
        .then(res => {
          this.chapterVideoList = res.data.allChapterVideo
        })
    },
    // 上一步按钮
    previous() {
      this.$router.push({path: '/course/info/' + this.courseId})
    },
    // 下一步按钮
    next() {
      this.$router.push({path: '/course/publish/' + this.courseId})
    },
    // 关闭弹框
    closeDialog() {
      this.dialogFormChapter = false
    },
    // 删除章节
    deleteChapterById(data) {
      this.$confirm('此操作将会删除章节是否继续', '提示', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          chapter.deleteChapter(data).then(res => {
            this.$message({
              type: 'success',
              message: '删除章节成功'
            })
            // 刷新章节
            this.getChapterVideo()
          })
        })
        .catch(res => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 保存章节
    saveChapter() {
      this.chapter.courseId = this.courseId
      chapter.addChapter(this.chapter)
        .then(res => {
          // 关闭弹框
          this.closeDialog()
          // 提示信息
          this.$message({
            type: 'success',
            message: '添加章节成功！'
          })
          // 刷新页面
          this.getChapterVideo()
        })
    },
    // 修改章节
    updateChapter() {
      chapter.updateChapter(this.chapter)
        .then(res => {
          // 关闭弹框
          this.closeDialog()
          // 提示信息
          this.$message({
            type: 'success',
            message: '修改章节成功'
          })
          this.chapter = {}
          this.getChapterVideo()
        })
    },
    // 保存并修改
    saveOrUpdate() {
      if (this.chapter.id === null) {
        this.saveChapter()
      } else {
        this.updateChapter()
      }
    },
  }
}
</script>

<style scoped>
#chapter {
  width: 70%;
  margin: auto;
}

#chapter >>> .el-tree-node__content {
  height: 50px;
  line-height: 50px;
  font-size: 18px;
  padding-left: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  padding-right: 8px;
}
</style>
